package br.com.keropizza.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import br.com.keropizza.dao.SaborDao;
import br.com.keropizza.dominio.Sabor;

@Transactional
@Controller
public class SaborController {

	@Autowired
	private SaborDao saborDao;

	@RequestMapping("novoSabor")
	public String novaSabor() {
		return "sabor/adiciona-sabor";
	}

	@RequestMapping("adicionaSabor")
	public String adicionaSabor(@Valid Sabor sabor, BindingResult result,
			Model model) {
		if (result.hasErrors()) {
			return "sabor/adiciona-sabor";
		}
		this.saborDao.adiciona(sabor);
		model.addAttribute("saborSalvo", sabor);
		return "sabor/adiciona-sabor";
	}

	@RequestMapping("listaSabores")
	public String listaSabor(Model model) {
		List<Sabor> sabores = this.saborDao.buscaTodasSabor();
		model.addAttribute("sabores", sabores);
		return "sabor/lista-sabor";
	}

	@RequestMapping("mostraSabor")
	public String mostraSabor(Long id, Model model) {
		Sabor sabor = this.saborDao.buscaPorId(id);
		model.addAttribute("sabor", sabor);
		return "sabor/mostra-sabor";
	}

	@RequestMapping("alteraSabor")
	public String alteraSabor(@Valid Sabor sabor, BindingResult result,
			Model model) {
		if (result.hasErrors()) {
			return "sabor/mostra-sabor";
		}
		this.saborDao.altera(sabor);
		model.addAttribute("sabor", sabor);
		return "redirect:listaSabor";
	}

	@RequestMapping("removeSabor")
	public String removeSabor(Sabor sabor) {
		this.saborDao.remove(sabor);
		return "redirect:listaSabor";
	}
}